using System;
using System.Configuration;
using System.Reflection;
using System.Collections.Generic;

namespace SpoonCore
{
	public class HandlerManager : IDisposable
	{
		private SpoonClient _client;
		private MessageHandler _handler;
		private List<IMessageHandler> _handlerList = new List<IMessageHandler>();

		public HandlerManager(SpoonClient client, MessageHandler handler)
		{
			_client = client;
			_handler = handler;
		}

		public void LoadHandler()
		{
			foreach (
				string item in
					ConfigurationManager.AppSettings["Handler"].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
			{
				Type type = Type.GetType(item.Trim());
				if (type != null)
				{
					ConstructorInfo con = type.GetConstructor(new Type[] { });
					if (con != null)
					{
						Object res = con.Invoke(new object[] { });
						if (res is IMessageHandler)
						{
							IMessageHandler handler = (IMessageHandler)res;
							handler.SetClient(_client);
							handler.RegisterHandler(_handler);
							_handlerList.Add(handler);
							//Console.WriteLine("Handler loaded: " + handler.GetType().FullName);
						}
						else
							Console.WriteLine("Class not member of IMessageHandler");
					}
					else
						Console.WriteLine("No constructor with no parameters");
				}
				else
					Console.WriteLine("Handler not found: " + item.Trim());
			}
		}

		public void Dispose()
		{
			foreach (IMessageHandler handler in _handlerList)
			{
				handler.Dispose();
			}
		}
	}
}